<?
/**
* Метод для обработки аякс-запросов для работы с документами
* напрямую экшн не вызывается
**/
class Action_Quest_DocAction extends RL_Handler{
	/**
	* @var Model_Quest
	**/
	private $model;
	private $oDoc;
	private $oQuest;

	public $ajax_functions = array(
		'ajax_docAction',
	);

	public function init() {
		$this->rh->useClass("Model_Item");
		$this->model = $this->ctx->mm->getModel("Quest");

		$this->oDoc = $this->model->getItem($this->params['item_id']);
		$this->oQuest = $this->model->getItem($this->params['quest_id']);
		$this->rh->UseClass('RL_URLGenerator');
	}

	public function process() {
 		// -- old theme HACK : 2008-05-21 : lucky -- {{{
		$community_skin = 'platonica';
		$tpl = $this->ctx->tpl;
		$community_model = $this->ctx->mm->getModel("Community");
		$community_model->setDefaultSkin($community_skin);
		$tpl->setSkin($community_skin);
		$views_php = $tpl->findFile('', 'views', $tpl->_skin, 'php');
		unset ($config);
		include $views_php; // got $config
		$this->ctx->rh->views->setViewConfig($config);
		// -- old theme HACK : 2008-05-21 : lucky -- }}}


	}

	public function ajax_docAction($actions, $votes, $isShowQuest, $btn_n=0, $use_simple_view=false) {
		$btn_n = (int)$btn_n;
		$node = $this->ctx->cp->add_node("quest");
		$node->set_data($this->oQuest->id);
		$node = $this->ctx->cp->add_node("doc");
		$node->set_data($this->oDoc->id);
		//права
		$actionsList = $this->model->getDocumentActions($this->oQuest, $this->oDoc);
		//действия
		$count = strlen($actions);
		for($i=0; $i<$count; $i++) {
			switch($actions[$i]) {
				case 'a':
				    if($actionsList['add'])
					   $this->model->setDocumentState
					       ($this->oQuest->id, $this->oDoc->id, Model_Quest::STATE_INQUEST);
					break;
				case 'v':
				    if($actionsList['vote']) {
    					$sVotes = explode(",",$votes);
    					foreach($sVotes as $sVote) {
    						list($voteId, $ball) = explode("=", $sVote);
    						$this->model->voteDoc($this->oDoc,$this->oQuest,$voteId, $ball);
    					}
    				}
					break;
				case 'f':
				    if($actionsList['final'])
    				    $this->model->setDocumentState
    						($this->oQuest->id, $this->oDoc->id, Model_Quest::STATE_INFINAL);
				    break;

			}
		}

		$this->use_simple_view = ($use_simple_view === 'false' ? 0 : 1);
		$this->questActions = $this->showQuestActions($btn_n);
		$this->btn_n = $btn_n;
		$this->isShowQuest = $isShowQuest;

		if ($this->use_simple_view) $this->showSimpleQuestPanel(); else
		 	$this->showQuestPanel();

	}

	private function showSimpleQuestPanel ()
	{
		$view = $this->rh->views->findByName('quest_doc_action_simple_ajax');
		$view->data['q'] = $this->questActions;
		$view->data['d'] = array('id'=>$this->oDoc->id);
		$view->data['is_quest'] = $this->isShowQuest;
		$node = $this->ctx->cp->add_node("content");
		$node->set_data($view->getContent());
	} // end of method showSimpleView

	private function showQuestPanel ()
	{
		$view = $this->rh->views->findByName('quest_doc_action_ajax');
		$view->data['q'] = $this->questActions;
		$view->data['d'] = array('id'=>$this->oDoc->id);
		$view->data['is_quest'] = $this->isShowQuest;
		$node = $this->ctx->cp->add_node("content");
		$node->set_data($view->getContent());
		$this->showQuestBtn();
		$this->showVoterCnt();
	} // end of method showQuestPanel

	private function showQuestBtn(){
		$view = $this->rh->views->findByName('quest_doc_action_quest_btn_ajax');
		$view->data['is_active'] = true;
		$view->data['quest'] = $this->oQuest->id;
		$view->data['doc_id'] = $this->oDoc->id;
		$view->data['*'] = $this->questActions;
		$view->data['is_quest'] = $this->isShowQuest;
		$node = $this->ctx->cp->add_node("quest_btn");
		$node->set_data($view->getContent());
	}

	private function showVoterCnt($actions, $votes, $isShowQuest, $btn_n){
		$view = $this->rh->views->findByName('quest_doc_action_cur_balls_btn_ajax');
		$view->data['is_active'] = true;
		$view->data['quest'] = $this->oQuest->id;
		$view->data['doc_id'] = $this->oDoc->id;
		$view->data['*'] = $this->questActions;
		$view->data['is_quest'] = $this->isShowQuest;
		$node = $this->ctx->cp->add_node("cur_balls_btn");
		$node->set_data($view->getContent());
	}

	public function showQuestActions($btn_n) {
		$this->module->aa->getInfo();
		$ug = new RL_URLGenerator($this->rh->router->getRule("show_quest"));
		$ug->setRouter($this->rh->router);
		$ug->setParams(array(
			"id_quest"		=> $this->oQuest->id,
			"community_url"	=>  $this->module->aa->acl_data['community_url'],
		));

		$ret = array(
			'id'	=> $this->oQuest->id,
			'title' => $this->oQuest->data['title'],
			'url' 	=> $ug->generateUrl(),
		);
		$actions = $this->model->getDocumentActions($this->oQuest,$this->oDoc);
		$ret['actions'] = $actions;
		$ret['btn_n'] = $btn_n;
		//получить все текущие баллы
		if($actions['cur_votes']) {
			$curBalls = $this->model->getCurrentBalls($this->oQuest, $this->oDoc);
			$ret['cur_count'] = $curBalls['count'];
			$ret['cur_balls'] = $curBalls['summ'];
		}
		//голосование/текущие баллы по номинациям
		if($actions['vote'] || $actions['cur_votes']) {
			$votes = $this->model->getVotes($this->oQuest);
			$questActions['votes'] = array();
			//отобразить все номиниции
			$votesCount = count($votes);
			for($i=0; $i<$votesCount; $i++) {
				$vote = $this->showVoteParams($votes[$i], $actions['vote']);

				$ret['votes'][$i] = $vote;
				//текущие результаты
				if($actions['cur_votes']) {
					$voteId = $votes[$i]['vote_id'];
					$ret['votes'][$i]['cur'] =
						$this->showCurVote($votes[$i],$curBalls['votes'][$voteId]);
				}
			}
		}
		$ret['voters'] = $this->model->getVotersCount($this->oQuest, $this->oDoc);
		return $ret;
	}

	private function showVoteParams($vote, $isVote=true) {
		$ret = array(
			'id'   	 => $vote['vote_id'],
			'name'   => $vote['name'],
			'method' => $vote['method'],
		);
		//если можно голосовать
		if($isVote) {
			$ret['variants'] = $this->getVoteVariants($vote);
			$ret['var_count'] = count($ret['variants']);
			//текущая оценка текущего пользователя (null, если не голосовал)
			$cur = $this->model->getUserVote($vote, $this->oQuest->id, $this->oDoc->id);
			if($cur !== null) {
				$ret['is_voted'] = 1;
				$ret['cur_vote'] = $cur;
			}
		}
		return $ret;
	}

	//бредятина, убить
	private function getVoteVariants($vote){
		switch($vote['method']) {
			case Model_Quest::VM_BINAR:
				return array(
					array('value'=>'-1', 'name'=>'-'),
					array('value'=>'1', 'name'=>'+'),
				);
			case Model_Quest::VM_SCALE:
				$ret = array();
				for($i=$vote['variants'][0]; $i<=$vote['variants'][1]; $i++) {
					$ret[] = array('value'=>$i, 'name'=>$i);
				}
				return $ret;
			case Model_Quest::VM_CATEGORY:
			case Model_Quest::VM_CATEGORIES:
				$ret = array();
				$count = count($vote['variants']);
				for($i=0; $i<$count; $i++) {
					$ret[] = array(
						'value'=>$i,
						'name'=>$vote['variants'][$i]
					);
				}
				return $ret;
			case Model_Quest::VM_TAGS:
				$ret = array();
				foreach($vote['variants'] as $variant) {
					$ret[] = array(
						'value'=>$variant,
						'name'=>$variant
					);
				}
				return $ret;
		}
	}

	private function showCurVote($vote, $cur){
		$ret = array(
			'val'	=> $cur['mid'],
		);
		switch($vote['method']) {
			case Model_Quest::VM_SCALE:
				$vs = $vote['variants'];
				$count = $vs[1] - $vs[0] + 1;
				if($count <= 10) {
					$ret['variants'] = array();
					for($i=$vs[0]; $i<=$vs[1]; $i++) {
						//записываем в варианты
						//0 - пустая звёздочк
						//1-3 - кусочки
						//4 - целая звёздочка
						if($i<=$cur['mid'])
							$val = 4;
						elseif($i>=$cur['mid']+1)
							$val = 0;
						else
							$val = round((1 + $cur['mid'] - $i)*4);
						$ret['variants'][] = $val;
					}
				}
				break;

		}
		return $ret;
	}
}
